import 'dart:async';

import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:amap_search_fluttify/amap_search_fluttify.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:gourmet/config/amap_config.dart';
import 'package:gourmet/event/index.dart';
import 'package:gourmet/route/index.dart';
import 'package:gourmet/utils/colors.dart';
import 'package:gourmet/utils/styles.dart';
import 'package:permission_handler/permission_handler.dart';

void main() {
  SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
    statusBarIconBrightness: Brightness.light,
    statusBarColor: Colors.transparent,
  ));
  runApp(const MyAppMain());
}

class MyAppMain extends StatefulWidget {
  const MyAppMain({super.key});

  @override
  State<MyAppMain> createState() => _MyAppMain();
}

class _MyAppMain extends State<MyAppMain> {
  final AMapFlutterLocation _locationPlugin = AMapFlutterLocation();

  StreamSubscription<Map<String, Object>>? _locationListener;

  @override
  void initState() {
    _location();
    _initAmap();
    super.initState();
  }

  void _initAmap() {
    AmapSearch.instance.init(AmapConfig.amapApiKeys.iosKey!);
    AmapSearch.instance.updatePrivacyShow(true);
    AmapSearch.instance.updatePrivacyAgree(true);
  }

  void _location() {
    /// 设置是否已经包含高德隐私政策并弹窗展示显示用户查看，如果未包含或者没有弹窗展示，高德定位SDK将不会工作
    ///
    /// 高德SDK合规使用方案请参考官网地址：https://lbs.amap.com/news/sdkhgsy
    /// <b>必须保证在调用定位功能之前调用， 建议首次启动App时弹出《隐私政策》并取得用户同意</b>
    ///
    /// 高德SDK合规使用方案请参考官网地址：https://lbs.amap.com/news/sdkhgsy
    ///
    /// [hasContains] 隐私声明中是否包含高德隐私政策说明
    ///
    /// [hasShow] 隐私权政策是否弹窗展示告知用户
    AMapFlutterLocation.updatePrivacyShow(true, true);

    /// 设置是否已经取得用户同意，如果未取得用户同意，高德定位SDK将不会工作
    ///
    /// 高德SDK合规使用方案请参考官网地址：https://lbs.amap.com/news/sdkhgsy
    ///
    /// <b>必须保证在调用定位功能之前调用, 建议首次启动App时弹出《隐私政策》并取得用户同意</b>
    ///
    /// [hasAgree] 隐私权政策是否已经取得用户同意
    AMapFlutterLocation.updatePrivacyAgree(true);

    /// 动态申请定位权限
    requestPermission();

    ///设置Android和iOS的apiKey<br>
    ///key的申请请参考高德开放平台官网说明<br>
    ///Android: https://lbs.amap.com/api/android-location-sdk/guide/create-project/get-key
    ///iOS: https://lbs.amap.com/api/ios-location-sdk/guide/create-project/get-key
    AMapFlutterLocation.setApiKey(
        AmapConfig.amapApiKeys.androidKey!, AmapConfig.amapApiKeys.iosKey!);

    ///iOS 获取native精度类型
    if (GetPlatform.isIOS) {
      requestAccuracyAuthorization();
    }

    ///注册定位结果监听
    _locationListener = _locationPlugin
        .onLocationChanged()
        .listen((Map<String, Object> result) {
      /// `callbackTime`:回调时间，格式为"yyyy-MM-dd HH:mm:ss"
      ///
      /// `locationTime`:定位时间， 格式为"yyyy-MM-dd HH:mm:ss"
      ///
      /// `locationType`:  定位类型， 具体类型可以参考https://lbs.amap.com/api/android-location-sdk/guide/utilities/location-type
      ///
      /// `latitude`:纬度
      ///
      /// `longitude`:精度
      ///
      /// `accuracy`:精确度
      ///
      /// `altitude`:海拔, android上只有locationType==1时才会有值
      ///
      /// `bearing`: 角度，android上只有locationType==1时才会有值
      ///
      /// `speed`:速度， android上只有locationType==1时才会有值
      ///
      /// `country`: 国家，android上只有通过[AMapLocationOption.needAddress]为true时才有可能返回值
      ///
      /// `province`: 省，android上只有通过[AMapLocationOption.needAddress]为true时才有可能返回值
      ///
      /// `city`: 城市，android上只有通过[AMapLocationOption.needAddress]为true时才有可能返回值
      ///
      /// `district`: 城镇（区），android上只有通过[AMapLocationOption.needAddress]为true时才有可能返回值
      ///
      /// `street`: 街道，android上只有通过[AMapLocationOption.needAddress]为true时才有可能返回值
      ///
      /// `streetNumber`: 门牌号，android上只有通过[AMapLocationOption.needAddress]为true时才有可能返回值
      ///
      /// `cityCode`: 城市编码，android上只有通过[AMapLocationOption.needAddress]为true时才有可能返回值
      ///
      /// `adCode`: 区域编码， android上只有通过[AMapLocationOption.needAddress]为true时才有可能返回值
      ///
      /// `address`: 地址信息， android上只有通过[AMapLocationOption.needAddress]为true时才有可能返回值
      ///
      /// `description`: 位置语义， android上只有通过[AMapLocationOption.needAddress]为true时才有可能返回值
      ///
      /// `errorCode`: 错误码，当定位失败时才会返回对应的错误码， 具体错误请参考：https://lbs.amap.com/api/android-location-sdk/guide/utilities/errorcode
      ///
      /// `errorInfo`: 错误信息， 当定位失败时才会返回
      // Get.log('result = $result');
      if (result['errorCode'] == 0) {
        eventBus.fire(LocationEvent(result));
      }
    });
  }

  /// 动态申请定位权限
  void requestPermission() async {
    // 申请权限
    bool hasLocationPermission = await requestLocationPermission();
    if (hasLocationPermission) {
      debugPrint('定位权限申请通过');

      /// 开始定位
      _startLocation();
    } else {
      debugPrint('定位权限申请不通过');
    }
  }

  ///获取iOS native的accuracyAuthorization类型
  void requestAccuracyAuthorization() async {
    AMapAccuracyAuthorization currentAccuracyAuthorization =
        await _locationPlugin.getSystemAccuracyAuthorization();
    if (currentAccuracyAuthorization ==
        AMapAccuracyAuthorization.AMapAccuracyAuthorizationFullAccuracy) {
      debugPrint('精确定位类型');
    } else if (currentAccuracyAuthorization ==
        AMapAccuracyAuthorization.AMapAccuracyAuthorizationReducedAccuracy) {
      debugPrint('模糊定位类型');
    } else {
      debugPrint('未知定位类型');
    }
  }

  /// 申请定位权限
  /// 授予定位权限返回true， 否则返回false
  Future<bool> requestLocationPermission() async {
    ///获取当前的权限
    var status = await Permission.location.status;
    if (status == PermissionStatus.granted) {
      ///已经授权
      return true;
    }

    ///未授权则发起一次申请
    status = await Permission.location.request();
    if (status == PermissionStatus.granted) {
      return true;
    }
    return false;
  }

  ///设置定位参数
  void _setLocationOption() {
    AMapLocationOption locationOption = AMapLocationOption();

    ///是否单次定位
    locationOption.onceLocation = false;

    ///是否需要返回逆地理信息
    locationOption.needAddress = true;

    ///逆地理信息的语言类型
    locationOption.geoLanguage = GeoLanguage.DEFAULT;

    locationOption.desiredLocationAccuracyAuthorizationMode =
        AMapLocationAccuracyAuthorizationMode.ReduceAccuracy;

    locationOption.fullAccuracyPurposeKey = 'AMapLocationScene';

    ///设置Android端连续定位的定位间隔
    locationOption.locationInterval = 2000;

    ///设置Android端的定位模式<br>
    ///可选值：<br>
    ///<li>[AMapLocationMode.Battery_Saving]</li>
    ///<li>[AMapLocationMode.Device_Sensors]</li>
    ///<li>[AMapLocationMode.Hight_Accuracy]</li>
    locationOption.locationMode = AMapLocationMode.Hight_Accuracy;

    ///设置iOS端的定位最小更新距离<br>
    locationOption.distanceFilter = -1;

    ///设置iOS端期望的定位精度
    /// 可选值：<br>
    /// <li>[DesiredAccuracy.Best] 最高精度</li>
    /// <li>[DesiredAccuracy.BestForNavigation] 适用于导航场景的高精度 </li>
    /// <li>[DesiredAccuracy.NearestTenMeters] 10米 </li>
    /// <li>[DesiredAccuracy.Kilometer] 1000米</li>
    /// <li>[DesiredAccuracy.ThreeKilometers] 3000米</li>
    locationOption.desiredAccuracy = DesiredAccuracy.Best;

    ///设置iOS端是否允许系统暂停定位
    locationOption.pausesLocationUpdatesAutomatically = false;

    ///将定位参数设置给定位插件
    _locationPlugin.setLocationOption(locationOption);
  }

  ///开始定位
  void _startLocation() {
    ///开始定位之前设置定位参数
    _setLocationOption();
    _locationPlugin.startLocation();
  }

  ///停止定位
  void _stopLocation() {
    _locationPlugin.stopLocation();
  }

  @override
  void dispose() {
    super.dispose();

    ///移除定位监听
    _locationListener?.cancel();

    _stopLocation();

    ///销毁定位
    _locationPlugin.destroy();
  }

  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: const Size(375, 667),
      minTextAdapt: true,
      splitScreenMode: true,
      useInheritedMediaQuery: true,
      ensureScreenSize: true,
      builder: (context, child) {
        return buildGetApp(context);
      },
    );
  }

  Widget buildGetApp(BuildContext context) {
    return GetMaterialApp(
      title: 'O2O外卖',
      debugShowCheckedModeBanner: false,
      color: Colors.transparent,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        dialogBackgroundColor: Colors.black45,
        dialogTheme: DialogTheme(
          backgroundColor: Colors.transparent,
          barrierColor: ColorsUtils.rgba(0, 0, 0, 0.298039215686275),
        ),
        useMaterial3: true,
        appBarTheme: AppBarTheme(
          iconTheme: IconThemeData(color: Colors.white, size: 20.w),
          centerTitle: true,
          titleSpacing: 0,
          titleTextStyle: StylesUtils.customTextStyle(
              fontSize: StylesUtils.fontSize16, fontWeight: FontWeight.w700),
          elevation: 0,
          surfaceTintColor: Colors.transparent,
          backgroundColor:
              ColorsUtils.parseColorFromHexString(ColorsUtils.colorF048),
          systemOverlayStyle: SystemUiOverlayStyle.light,
        ),
      ),
      darkTheme: ThemeData(
        brightness: Brightness.light,
      ),
      themeMode: ThemeMode.system,
      initialRoute: Routes.home,
      getPages: Routes.pages,
      transitionDuration: const Duration(milliseconds: 500),
      defaultTransition: Transition.cupertino,
    );
  }
}
